package org.zyg 

// 拉取job在数据库中的信息
def getMysqlMsg(jobName) {
    println "===========获取${jobName}信息============"
    getDatabaseConnection(type: 'GLOBAL') {
        def result = sql("SELECT *  FROM job_msg WHERE job_name=\"${jobName}\"")
        if (result.size() > 1 ) {
            error "${jobName} 在数据库中数据不唯一，请管理员检查！"
        } else if (result.size() == 0 ) {
            error "${jobName} 未录入数据库中，请管理员检查！"
        } 
        return result
    }
}


// 代码检出
def gitCheckOut(gitUrl, gitBranch, cId='git-root') {
    echo '清理工作目录'
    deleteDir()
    println "===========检出仓库${gitUrl}的${gitBranch}分支============"
    checkout(
        [$class: 'GitSCM', doGenerateSubmoduleConfigurations: false, submoduleCfg: [], extensions: [[$class: 'CloneOption', depth: 1, noTags: false, reference: '', shallow: true]],
        branches: [[name: gitBranch]],userRemoteConfigs: [[url: gitUrl, credentialsId: cId]]]
    )
}

// java 代码构建
def javaBuild(archivePath) {
    def statusCode = sh returnStatus: true, script: "mvn clean install" // 全局引入tools后 这里就不需要在source 环境变量文件了
    if (statusCode!=0) {
        error "构建出现错误！！！请开发在本地打包测试后再提交构建"
    }
    
    echo '检查构建产物是否存在'
    echo '检查产物名称是否符合规范'
    script {
        if (fileExists(archivePath)){
            // 归档构建产物
            archiveArtifacts artifacts: archivePath, fingerprint: true
        } else {
            error "未找到构建成品${archivePath}，请研发检查项目pom.xml的输出路径以及包名是否规范"
        }
    }
}

// java 代码部署
def javaDeploy(platForm, jobName, jobPort) {
    def start_script = libraryResource('start_project.sh')
    writeFile file: 'start_up.sh', text: start_script
    // // 运行 Ansible 命令，并捕获退出码
    def exitCode = sh(script: """
        ansible ${platForm}-${jobName} -m shell -a "mkdir -p /data/update/${jobName}"
        ansible ${platForm}-${jobName} -m copy -a "src=target/${jobName}.jar dest=/data/update/${jobName}/${jobName}.jar"
        ansible ${platForm}-${jobName} -m script -a "start_up.sh ${jobName} ${jobPort}"
    """, returnStatus: true)
    
    // 根据退出码进行处理
    if (exitCode != 0) {
        echo "Ansible 部署出现异常，请运维人员检查~！"
        error "Ansible 部署出现异常，请运维人员检查~！"
    } else {
        echo "部署成功."
    }
}

// 钉钉消息发送通知
def dingMsgSend(robotID, platFrom, jobName, buildUrl, branchMsg, buildUserName, buildResut) {
    dingtalk (
        robot: robotID,
        type: 'MARKDOWN',
        title: "[ ${jobName}  - 构建${buildResut}提醒](${buildUrl})",
        text: [
            "# [ ${jobName}  - 构建${buildResut}提醒](${buildUrl})",
            "---",
            "- 项目名称： ${jobName} ",
            "- 构建分支： ${branchMsg}",
            "- 构建人： ${buildUserName}",
            "- 构建  Url ：${buildUrl}",
            "- 任务持续时间: ${currentBuild.duration/1000}秒"
        ]
    )
}